package com.freedom.start.common.base;

import com.freedom.start.utils.IDGenerator;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author: zhenggang.liu
 * @Date: 2019/12/28 9:36
 */
public class BaseCrudService<D extends BaseCrudDao<T>, T extends BaseCrudEntity> {

    /**
     * 持久层对象
     */
    @Autowired
    protected D dao;

    /**
     * 日志对象
     */
    protected Logger logger = LoggerFactory.getLogger(getClass());

    public T get(String id) {
        return dao.getById(id);
    }

    /**
     * 插入或是修改，根据id是否存在调用不同的方法
     *
     * @param entity
     * @return
     */
    public final int save(T entity) {
        if (entity.getId() == null || entity.getId().length() == 0) {
            entity.setId(IDGenerator.uuid());
            entity.setCreateDate(LocalDateTime.now());
            entity.setUpdateDate(LocalDateTime.now());
            entity.setCreateBy("1");
            entity.setUpdateBy("1");
            resetFieldValue(entity);
            return dao.insert(entity);
        } else {
            entity.setUpdateBy("1");
            entity.setUpdateDate(LocalDateTime.now());
            resetFieldValue(entity);
            return dao.update(entity);
        }
    }

    /**
     * 模板方法，用于子类service改变entity的其他属性
     *
     * @param entity
     */
    protected void resetFieldValue(T entity) {
    }

    /**
     * 返回所有符合条件的记录
     *
     * @return
     */
    public List<T> findAll(T entity) {
        return dao.findList(entity);
    }

    /**
     * 返回分页对象
     *
     * @param entity
     * @return
     */
    public PageInfo<T> findPage(T entity) {
        List<T> list = dao.findList(entity);
        return new PageInfo<T>(list);
    }

    /**
     * 返回easyui框架所需数据列表和格式
     *
     * @param entity
     * @return
     */
    public Map<String, Object> findPageForEasyUI(HttpServletRequest request, T entity) {
        String page = request.getParameter("page");
        String rows = request.getParameter("rows");
        if (StringUtils.isNumeric(page) && StringUtils.isNumeric(rows)) {
            PageHelper.startPage(Integer.parseInt(page), Integer.parseInt(rows));
        } else {
            logger.error("An error occurred while getting form parameters 'page' or 'rows',the entity is : {}", entity.getClass());
        }
        List<T> list = dao.findList(entity);
        HashMap<String, Object> map = new HashMap<>();
        map.put("total", ((Page) list).getTotal());
        map.put("rows", list);

        return map;
    }

    /**
     * 删除一条及多条记录
     *
     * @param ids
     * @return
     */
    public int deleteBatch(String ids) {
        if (ids.endsWith(",")) {
            ids = ids.substring(0, ids.length() - 1);
        }
        String[] idArray = ids.split(",");
        return dao.deleteBatch(idArray);
    }
}
